<template>
    <div class="publish-goods">
        <el-card class="card">
            <template #header>
                <div class="card-header">发布商品</div>
            </template>
            <el-form :model="goodsForm" ref="goodsFormRef" label-width="120px">
                <el-form-item label="商品名称">
                    <el-input v-model="goodsForm.name" placeholder="请输入商品名称"></el-input>
                </el-form-item>
                <el-form-item label="商品价格">
                    <el-input v-model.number="goodsForm.salePrice" placeholder="请输入商品价格"></el-input>
                </el-form-item>
                <el-form-item label="商品库存">
                    <el-input v-model.number="goodsForm.initialStock" placeholder="请输入商品库存"></el-input>
                </el-form-item>
                <el-form-item label="商品描述">
                    <el-input type="textarea" v-model="goodsForm.description" placeholder="请输入商品描述"></el-input>
                </el-form-item>
                <!-- 添加分类下拉框 -->
                <el-form-item label="商品分类">
                    <el-select v-model="goodsForm.categoryId" placeholder="请选择">
                        <el-option
                            v-for="item in options"
                            :key="item.id"
                            :label="item.categoryName"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品图片">
                    <el-upload
                        name="photo"
                        list-type="picture-card"
                        class="avatar-uploader"
                        action="http://localhost:8888/product/upload"
                        :show-file-list="true"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove"
                        :file-list="fileList">
                        <i class="el-icon-plus"></i>
                        <!-- 放大图片显示 -->
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm">提交</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
export default {
    data() {
        return {
            goodsForm: {
                name: '',
                salePrice: 0,
                initialStock: 0,
                description: '',
                imageUrls: [],
                categoryId: null, // 确保有这个字段
                categoryName: ''
            },
            dialogVisible: false,
            dialogImageUrl: '',
            fileList: [],
            categoryList: [], // 用于存储商品分类数据
            // 添加分类下拉框数据
            options: [],
            value: ''
        };
    },
    methods: {
        fetchCategories() {
            // 假设这里的接口返回分类数据，需要根据实际情况修改
            this.$axios.post('/productCategory/listProductCategory').then(response => {
                this.options = response.data;
            }).catch(error => {
                console.error('获取商品分类数据失败', error);
            });
        },
        submitForm() {
            this.goodsForm.imageUrls = [];
            // 获取当前图片上传中的图片路径
            for (let i = 0; i < this.fileList.length; i++) {
                let file = this.fileList[i];
                this.goodsForm.imageUrls.push(file.response);
            }
            console.log('提交表单数据', this.goodsForm);
            // 修改请求路径
            this.$axios.post(`/product/add`, this.goodsForm).then(r => {
                console.log('表单提交成功', this.goodsForm);
                this.$message.success('商品发布成功');
                this.resetForm();
            }).catch(error => {
                console.error('表单提交失败', error);
                this.$message.error('商品发布失败');
            });
        },
        resetForm() {
            this.$refs.goodsFormRef.resetFields();
            this.goodsForm.imageUrls = []; // 重置图片URL数组
            this.goodsForm.categoryId = ''; // 重置分类选择
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
            const index = this.fileList.indexOf(file);
            if (index > -1) {
                this.fileList.splice(index, 1);
            }
            this.goodsForm.imageUrls = this.fileList.map(file => file.response);
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleAvatarSuccess(res, file) {
            console.log('完整响应 res:', res); // 新增日志，查看响应结构
            // 假设先临时检查res是否存在
            if (!res) {
                console.error('上传响应res为undefined');
                return;
            }
            // 根据实际响应调整，假设后端返回{ data: { url: '图片路径' } }
            file.response = res.data?.url || res.url || ''; // 先兼容可能的结构
            this.fileList.push(file);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是JPG格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过2MB!');
            }
            return isJPG && isLt2M;
        },
    },
    created() {
        // 在组件创建时调用获取分类数据的接口
        this.fetchCategories();
    },
};
</script>

<style scoped>
.publish-goods {
    padding: 20px;
}

.card {
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-header {
    font-size: 18px;
    font-weight: bold;
}
</style>